var util = require('../utils/util');
var daoUtil = require('../utils/daoUtil');
var deal = require('../class/stockDeal');

module.exports = {

    create: function (params, cb) {
        var validate = daoUtil.validate(['num','createUid', 'price','stockChannelId','dealDate'], params);
        if(!validate.valid){
            cb(validate.error);
            return;
        }
        // params.positionNum = params.price*params.num;
        daoUtil.proxy(function(models){
            var stockdeal = new deal();
            stockdeal.init(params);
            models.stock_deal.create(stockdeal.getParams(), function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    update: function (params, cb) {
        var validate = daoUtil.validate(['rowId','num'| 'cost'|'dealDate'|'price'|'stockChannelId'], params);
        if(!validate.valid){
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function(models){
            var stockDeal = new stockDeal();
            stockDeal.init(params);
            models.stock_deal.update({rowId: params.rowId}, stockDeal.getParams()).exec(function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    get:function (rowId,cb) {
        daoUtil.proxy(function(models){
            models.stock_deal.find().exec(function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{

                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    /*获取时间内所有交易成本*/
    getAllInDate:function(params,cb){
        var validate = daoUtil.validate(['stockChannelIds'], params);
        if(!validate.valid){
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function(models){
            var sql = "select sum(price*num) val,sum(num) nums,substring_index((select stockCode from tb_dic_stock where rowId = (select stockId from tb_stock_channel where rowId = a.stockChannelId)),'.',1)stockCode from (select price,(case when type = 0 then num*-1  when type = 1 then num end)num,stockChannelId,dealDate from tb_stock_deal  )a where 1 = 1 ";
            if(params.startDate){
                sql += " and dealDate >= '"+params.startDate+"' ";
            }
            if(params.endDate){
                sql += " and dealDate < '"+params.endDate+"' ";
            }
            var i = 0;
            if(params.stockChannelIds && params.stockChannelIds.length >0 ){
                sql += ' and stockChannelId in ( ';
                for (stockChannelId of params.stockChannelIds) {
                    sql += "'" + stockChannelId.rowId + "'";
                    if (i < params.stockChannelIds.length - 1)
                        sql += ",";
                    i++;
                }
                sql += " )";
            }
            sql += " group by stockChannelId";
            models.stock_deal.query(sql, function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{

                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    //获取每个股票最新一条交易记录，得到最新的成本和总共股票数量
    getByStockChannelIds:function (params,cb) {
        var validate = daoUtil.validate(['stockChannelIds'], params);
        if(!validate.valid){
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function(models){
            models.stock_deal.find({'stockChannelId':params.stockChannelIds,'cost':{'!':null}},{sort:'createdAt desc'}).max('createdAt','cost','dealDate').sum('num','positionNum').groupBy('stockChannelId').exec(function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{

                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    //获取每个股票最新一条交易记录，得到最新的成本和总共股票数量,stockChannelId转stockCode
    getLaseDealByStockChannelIds:function (params,cb) {
        var validate = daoUtil.validate(['stockChannelIds'], params);
        if(!validate.valid){
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function(models){
            models.stock_deal.find({'stockChannelId':params.stockChannelIds,'cost':{'!':null}},{sort:'createdAt desc'}).max('createdAt','cost').sum('num','positionNum').groupBy('stockChannelId').exec(function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{

                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    list: function (params, cb) {
        var validate = daoUtil.validate(['stockChannelIds'], params);
        if(!validate.valid){
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function(models){
            models.stock_deal.find({'stockChannelId':params.stockChannelIds,sort:'createdAt desc'}).populate('stockChannelId').populate('createUid').exec(function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    findLastDealByChannel: function(params,cb){
        var validate = daoUtil.validate(['stockChannelId'], params);
        if(!validate.valid){
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function(models){
            models.stock_deal.find({'stockChannelId':params.stockChannelId,sort:'createdAt desc'}).populate('stockChannelId').populate('createUid').exec(function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    findMinDealByChannel: function(params,cb){
        var validate = daoUtil.validate(['stockChannelId'], params);
        if(!validate.valid){
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function(models){
            models.stock_deal.find({'stockChannelId':params.stockChannelId,sort:'createdAt asc'}).populate('stockChannelId').populate('createUid').exec(function (err, data) {
                if (err || !data) {
                    console.log(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(data));
                }
            });
        },cb);
    },
    deleteByIds:function (rowIds, cb) {
        daoUtil.proxy(function(models){
            models.stock_deal.destroy({rowId:rowIds}).exec(function (err, result) {
                if (err) {
                    console.log(err);
                    cb(util.getSysError());
                }else{
                    cb(null, util.getSuccessRes(result));
                }
            });
        },cb);
    }
};